package p.ithorns.framework.common.future;

import com.google.common.eventbus.Subscribe;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Device
 * TODO
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/12/11 21:23
 */
public class Device {

   final Random random = new Random();

    ExecutorService executor = Executors.newFixedThreadPool(3);

    @Subscribe
    public void execute(final Command cmd) {
        System.out.println("Device=====> 收到指令：" + cmd);
        SyncFuture<Object> future = FutureHolder.get(cmd);
        final String cmd1 = cmd.getCmd();
        executor.execute(() -> {
            delay(cmd1);
            future.set(String.format("==> Hello, I'm the Result for [%s]!", cmd1));
        });
    }

    private void delay(String cmd) {
        long delay = random.nextInt(1000) + 200;
        System.out.println(cmd + " :|---> delay：" + delay);
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
